<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="教师工号" prop="jobNumber">
            <el-input v-model="queryParams.jobNumber" placeholder="请输入教师工号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="教师名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入教师名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="教学学科" prop="subjectId">
             <el-select v-model="queryParams.subjectId"  clearable  placeholder="请选择学科" >
            <el-option v-for="dict in subjectOptions" :key="dict.id" :label="dict.subjectName" :value="dict.id"></el-option>
             </el-select>
          </el-form-item>
          <el-form-item label="学校" prop="deptId">
            <!-- <el-tree-select
                clearable
                v-model="queryParams.deptId"
                :data="deptOptions"
                :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                value-key="deptId"
                placeholder="选择学校"
               :render-after-expand="false"
              /> -->
            <el-select v-model="queryParams.deptId" placeholder="请选择学校" clearable :disabled="!(userId === 1 && tenantDisabled)">
              <el-option v-for="item in tenantOptions" :key="item.tenantId" :label="item.companyName" :value="item.tenantId"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            <el-button type="primary" @click="handleAdd" v-hasPermi="['core:teacher:add']">新增</el-button>
            <el-button type="primary" @click="handleImport" v-hasPermi="['']">导入</el-button>
            <el-button type="primary" @click="handleExport" v-hasPermi="['core:teacher:export']">导出</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <h2>教师列表</h2>
      </template>
      <el-table v-loading="loading" :data="teacherList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="id" align="center" prop="id" v-if="false" />
        <el-table-column label="教师工号" align="center" prop="jobNumber" />
        <el-table-column label="教师名称" align="center" prop="name" />
        <el-table-column label="手机号" align="center" prop="phoneNumber" />
        <el-table-column label="学校" align="center" prop="deptId" >
          <template #default="scope">
            {{getTenantById(tenantOptions,scope.row.deptId)}}
          </template>
        </el-table-column>
        <el-table-column label="教学学科" align="center" prop="subjectId" >
          <template #default="scope">
            {{ getSubjectNameById(subjectOptions, scope.row.subjectId) }}
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="100">
          <template #default="scope">
              <el-button type="text" size="small" @click="handleUpdate(scope.row)" v-hasPermi="['core:teacher:edit']">编辑</el-button>
              <el-button type="text" size="small" @click="handleDelete(scope.row)" v-hasPermi="['core:teacher:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改教师管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="teacherFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学校" prop="deptId"  v-if="userId === 1 && tenantDisabled">
          <!-- <el-tree-select
               clearable
                v-model="form.deptId"
                :data="deptOptions"
                :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                value-key="deptId"
                placeholder="选择学校"
                :render-after-expand="false"
              /> -->
          <el-select v-model="form.deptId" placeholder="请选择学校" >
            <el-option v-for="item in tenantOptions" :key="item.tenantId" :label="item.companyName" :value="item.tenantId"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="教师工号" prop="jobNumber">
          <el-input v-model="form.jobNumber" clearable placeholder="请输入教师工号" />
        </el-form-item>
        <el-form-item label="教师名称" prop="name">
          <el-input v-model="form.name"  clearable placeholder="请输入教师名称" />
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" type="tel" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="学科" prop="subjectId">
           <el-select v-model="form.subjectId"  clearable  placeholder="请选择学科" >
            <el-option v-for="dict in subjectOptions" :key="dict.id" :label="dict.subjectName" :value="dict.id"></el-option>
             </el-select>
        </el-form-item>
        
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="form.roleIds" filterable multiple placeholder="请选择">
            <el-option
              v-for="item in roleOptions"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
              :disabled="item.status == '1'"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" clearable placeholder="请输入备注" />
        </el-form-item>
       
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
     <!-- 导入对话框 -->
     <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload">
          <i-ep-upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <div class="el-upload__tip"><el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据</div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <!-- <el-button type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link> -->
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Teacher" lang="ts">
import { listTeacher, getTeacher, delTeacher, addTeacher, updateTeacher } from '@/api/core/teacher';
import { TeacherVO, TeacherQuery, TeacherForm } from '@/api/core/teacher/types';
import { globalHeaders } from '@/utils/request';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
import api from '@/api/system/user';
import { RoleVO } from '@/api/system/role/types';
const roleOptions = ref<RoleVO[]>([]);

/** 公共方法 */ 
import { getSubjectNameById,getTenantById } from '@/utils/index';
// 学校
import { useSchoolList,useTenantlList } from '@/composables/useSchoolList';
const { deptOptions, fetchSchoolList } = useSchoolList();
//学校改租户数据
const { tenantOptions, fetchTenantlList,tenantDisabled} = useTenantlList();
import useUserStore from '@/store/modules/user';
const userStore = useUserStore();
const userId = ref(userStore.userId);
const tenantId = ref(userStore.tenantId)
//学科
import { useSubjectList } from '@/composables/useSubjectList';
const { subjectOptions, fetchSubjectList } = useSubjectList();
/**  */ 

const teacherList = ref<TeacherVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const teacherFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
/*** 用户导入参数 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/core/teacher/import'
});
const uploadRef = ref<ElUploadInstance>();

const initFormData: TeacherForm = {
  name: undefined,
  phoneNumber: undefined,
  subjectId: undefined,
  deptId: undefined,
  remark: undefined,
  jobNumber: undefined,
  roleIds:undefined,
}
const data = reactive<PageData<TeacherForm, TeacherQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: undefined,
    name: undefined,
    phoneNumber: undefined,
    subjectId: undefined,
    deptId: undefined,
    jobNumber: undefined,
    params: {
    }
  },
  rules: {
    name: [
      { required: true, message: "教师名称不能为空", trigger: "blur" }
    ],
    phoneNumber: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码格式', trigger: 'blur' }
        ],
    deptId: [
      { required: true, message: "学校不能为空", trigger: "blur" }
    ],
    jobNumber: [
      { required: true, message: "教师工号不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 导入按钮操作 */
const handleImport = () => {
  upload.title = '教师导入';
  upload.open = true;
};
// /** 下载模板操作 */
// const importTemplate = () => {
//   proxy?.download('system/user/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`);
// };
/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {
    dangerouslyUseHTMLString: true
  });
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}

/** 查询教师管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listTeacher(queryParams.value);
  teacherList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  teacherFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: TeacherVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  const { data } = await api.getUser();
  roleOptions.value = data.roles;

  dialog.visible = true;
  dialog.title = "新增教师";
  
}

/** 修改按钮操作 */
const handleUpdate = async (row?: TeacherVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getTeacher(_id);
  Object.assign(form.value, res.data);

  const { data } = await api.getUser();
  roleOptions.value = data.roles;

  dialog.visible = true;
  dialog.title = "编辑教师";
}

/** 提交按钮 */
const submitForm = () => {
  teacherFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      //如果当前登录用户是管理员，学校用选择字段；
      if(userId.value === 1 && tenantDisabled.value){

      }else{ 
        //是租户，学校默认传当前用户tenantId
        form.value.deptId = tenantId;
      }

      if (form.value.id) {
        await updateTeacher(form.value).finally(() =>  buttonLoading.value = false);
        proxy?.$modal.msgSuccess("修改成功");
      } else {
        await addTeacher(form.value).finally(() =>  buttonLoading.value = false);
        proxy?.$modal.msgSuccess("新增成功");
      }
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: TeacherVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除教师管理编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delTeacher(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('core/teacher/export', {
    ...queryParams.value
  }, `teacher_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  console.log("====",userId.value,tenantDisabled.value,!(userId.value === 1 && tenantDisabled.value))
  if(!(userId.value === 1 && tenantDisabled.value)){
    // queryParams.value.deptId = getTenantById(tenantOptions.value,tenantId.value)
    queryParams.value.deptId = Number(tenantId.value) ;
  }
  getList();

  fetchSchoolList();
  fetchSubjectList
});
</script>
